package com.voicechat.firstmet.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.opensource.svgaplayer.SVGAImageView;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.GoldDepositsActivity;
import com.voicechat.firstmet.activity.IMChatActivity;
import com.voicechat.firstmet.adapter.MsgGifGridViewAdapter;
import com.voicechat.firstmet.adapter.ViewPagerAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.realm.ListBean;
import com.voicechat.firstmet.utils.RealmUtils;
import com.voicechat.firstmet.view.CirclePageIndicator;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment
 * @ClassName: IMSendGifFragment
 * @Description: 发送的礼物布局
 * @Author: ljp
 * @CreateDate: 2018/11/13 9:44
 * @Version: 1.0
 */
public class IMSendGifFragment extends BaseFragment {
    @BindView(R.id.view_pager_gif)
    ViewPager viewPagerGif;
    @BindView(R.id.tv_gold_sum)
    TextView tvGoldSum;
    @BindView(R.id.linear_recharge)
    LinearLayout linearRecharge;
    @BindView(R.id.tv_send)
    TextView tvSend;
    Unbinder unbinder;
    @BindView(R.id.ll_point_group)
    CirclePageIndicator llPointGroup;
    private List<ListBean> listBeans;
    public static int gridColumn = 4;//grid的列数
    public static int gridNum = 8;//grid的一页总数
    private ViewPagerAdapter mAdapter;
    private List<GridView> gridViews;
    private ListBean giftBean;//选中的礼物
    private static String otherId;
    private String TAG = "IMSendGifFragment";
    public static SVGAImageView svgaImageView;
    private int number;
    private MsgGifGridViewAdapter adapter;
    private int posi;
    public static String FLAG = "gift";//送礼物广播
    private SendGift sendGift;

    public void setSendGift(SendGift sendGift) {
        this.sendGift = sendGift;
    }

    public static IMSendGifFragment newInstance() {
        IMSendGifFragment fragment = new IMSendGifFragment();
        return fragment;
    }
    @Override
    protected int loadLayout() {
        return R.layout.fragment_msg_gif;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        giftBean = null;
        initView();
        initDatas();
    }

    public static void setSvgaImageView(SVGAImageView svgaImageView) {
        IMSendGifFragment.svgaImageView = svgaImageView;
    }
    public static IMSendGifFragment newInstance(String id) {
        IMSendGifFragment fragment = new IMSendGifFragment();
        otherId = id;
        return fragment;
    }
    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2018/11/13 10:07
     * @author: ljp
     */
    private void initView() {
        gridViews = new ArrayList<>();
        listBeans = new ArrayList<>();
        listBeans.addAll(RealmUtils.getInstance()
                .getRealm()
                .where(ListBean.class)
                .findAll());
        mAdapter = new ViewPagerAdapter();
        viewPagerGif.setAdapter(mAdapter);
        llPointGroup.setVisibility(View.VISIBLE);
        llPointGroup.setViewPager(viewPagerGif);
        initHttpGetGold();
        linearRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, GoldDepositsActivity.class);
                intent.putExtra("diamondSum",Integer.parseInt(tvGoldSum.getText().toString()));
                startActivity(intent);
               /* Uri uri = Uri.parse("https://www.chujian.live/faint-service/static/h5/app/rechargeh5.html?id="+
                        IMChatActivity.mySeleInfo.getNumber()+"&balanceNumber="+tvGoldSum.getText().toString());
                Log.i(TAG, "onClick: --------"+uri.toString());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);*/
            }
        });

        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (giftBean != null) {
                    //BroadcastManager.getInstance(App.getContext()).sendBroadcast(FLAG,giftBean);
                   // sendGift.sendGift(giftBean);
                    if(getActivity() != null){
                        ((IMChatActivity) getActivity()).initService(giftBean);
                    }

                    /*MeInfoService.sendGift(IMChatActivity.mySeleInfo.getId(), IMChatActivity.token, IMChatActivity.deviceInfo, otherId, giftBean.getId(),
                            giftBean.getGold() + "", PersonDataService.GIF_TYPE.GIF_GET, "", "1", "").subscribe(result -> {
                        Log.i(TAG, "onClick: ------" + result.toString());
                        if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                            toast_MakeText("送礼成功！");
                                if(!TextUtils.isEmpty(giftBean.getAnimationUrl())){
                                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("load",giftBean);
                                }else {
                                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("gift",giftBean);
                                }
                        }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_GOLD) {
                            toast_MakeText("金币余额不足，请充值！");
                        } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL) {
                            toast_MakeText("送礼失败，请重试！");
                        }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN){
                            Utils.setToken(context);
                        }
                    }, throwable -> {
                        Log.i(TAG, "onClick: -----" + throwable.toString());
                    });*/
                } else {
                    toast_MakeText("请选择礼物");
                }

            }
        });
    }

    public void setMoney(){
        initHttpGetGold();
    }

    public void setGiftBean(ListBean giftBean) {
        this.giftBean = giftBean;
        if(adapter != null){
            adapter.setCheckd(false,posi);
        }
    }

    private void initDatas() {
        //计算viewpager一共显示几页
        int pageSize = listBeans.size() % gridNum == 0
                ? listBeans.size() / gridNum
                : listBeans.size() / gridNum + 1;
        for (int i = 0; i < pageSize; i++) {
            GridView gridView = new GridView(activity);
            MsgGifGridViewAdapter adapter = new MsgGifGridViewAdapter(listBeans, i);
            gridView.setNumColumns(gridColumn);
            gridView.setHorizontalSpacing(5);
            gridView.setVerticalSpacing(10);
            gridView.setAdapter(adapter);
            int finalI = i;
            adapter.setItemClick(new MsgGifGridViewAdapter.ItemClick() {
                @Override
                public void setItemClick(int position) {
                }
            });
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    number = number+1;
                    adapter.setCheckd(true,position);
                    adapter.notifyDataSetChanged();
                    giftBean = adapter.getItem(position);
                    posi = position;

                    //toast_MakeText(adapter.getItem(position)+"");
                }
            });
            gridViews.add(gridView);
        }
        mAdapter.add(gridViews);
    }

    /**
     * @return
     * @method
     * @description 余额请求
     * @date: 2018/11/7 14:39
     * @author: ljp
     */
    private void initHttpGetGold() {
        MeInfoService.goldDiamond(IMChatActivity.mySeleInfo.getId(), IMChatActivity.token, IMChatActivity.deviceInfo).subscribe(goldBean -> {
            //Log.i(TAG, "initHttp: -------"+goldBean.getObject().toString());
            if (goldBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                tvGoldSum.setText(goldBean.getObject().getGold() + "");
            } else {
                toast_MakeText(goldBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "initHttp: -----" + throwable.toString());
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
    public interface SendGift{
        void sendGift(ListBean data);
    }
}
